package com.java110.cust.bmo.govPersonDie.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.cust.bmo.govPersonDie.ISaveGovPersonDieBMO;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.file.FileDto;
import com.java110.dto.govOldPerson.GovOldPersonDto;
import com.java110.dto.govPerson.GovPersonDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.assets.IFileRelInnerServiceSMO;
import com.java110.intf.cust.IGovOldPersonInnerServiceSMO;
import com.java110.intf.cust.IGovPersonInnerServiceSMO;
import com.java110.intf.cust.IUserInnerServiceSMO;
import com.java110.intf.engine.IFileInnerServiceSMO;
import com.java110.po.fileRel.FileRelPo;
import com.java110.po.govOldPerson.GovOldPersonPo;
import com.java110.po.govPerson.GovPersonPo;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.java110.core.context.DataFlowContext;
import com.java110.po.govPersonDie.GovPersonDiePo;
import com.java110.intf.cust.IGovPersonDieInnerServiceSMO;
import com.java110.utils.constant.BusinessTypeConstant;
import com.java110.utils.constant.CommonConstant;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("saveGovPersonDieBMOImpl")
public class SaveGovPersonDieBMOImpl implements ISaveGovPersonDieBMO {

    @Autowired
    private IGovPersonDieInnerServiceSMO govPersonDieInnerServiceSMOImpl;
    @Autowired
    private IGovPersonInnerServiceSMO govPersonInnerServiceSMOImpl;
    @Autowired
    private IUserInnerServiceSMO userInnerServiceSMOImpl;
    @Autowired
    private IGovOldPersonInnerServiceSMO govOldPersonInnerServiceSMOImpl;
    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;
    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;
    /**
     * 添加小区信息
     *
     * @param govPersonDiePo
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> save(GovPersonDiePo govPersonDiePo) {

        govPersonDiePo.setDieId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_dieId));
        int flag = govPersonDieInnerServiceSMOImpl.saveGovPersonDie(govPersonDiePo);

        if (flag > 0) {
        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
    }

    @Java110Transactional
    public ResponseEntity<String> savePhone(GovPersonDiePo govPersonDiePo,JSONArray photos) {
        UserDto userDto = new UserDto();
        userDto.setUserId(govPersonDiePo.getUserId());
        List<UserDto> userDtos = userInnerServiceSMOImpl.getUsers(userDto);
        Assert.listOnlyOne(userDtos, "用户不存在");
        //往人员、老人库库添加
        GovPersonPo govPersonPo = new GovPersonPo();
        GovOldPersonPo govOldPersonPo  = new GovOldPersonPo();
        govPersonPo.setCaId(govPersonDiePo.getCaId());
        govPersonPo.setNation(govPersonDiePo.getNation());
        govPersonPo.setPersonName(govPersonDiePo.getPersonName());
        govPersonPo.setIdCard(govPersonDiePo.getIdCard());
        govOldPersonPo.setCaId(govPersonDiePo.getCaId());
        govOldPersonPo.setGovCommunityId(govPersonDiePo.getGovCommunityId());
        doGovPersonPo(userDtos.get(0),govPersonPo,govOldPersonPo);
        govPersonDiePo.setDieId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_dieId));
        govPersonDiePo.setGovPersonId(govPersonPo.getGovPersonId());
        for (int _photoIndex = 0; _photoIndex < photos.size(); _photoIndex++) {
            FileDto fileDto = new FileDto();
            fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
            fileDto.setFileName(fileDto.getFileId());
            fileDto.setContext(photos.getJSONObject(_photoIndex).getString("photo"));
            fileDto.setSuffix("jpeg");
            String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);
            FileRelPo fileRelPo = new FileRelPo();
            fileRelPo.setFileRelId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_fileRelId));
            fileRelPo.setFileName(fileName);
            fileRelPo.setRelType("90300");
            fileRelPo.setObjId(govPersonDiePo.getDieId());
            fileRelInnerServiceSMOImpl.saveFileRel(fileRelPo);
        }
        int flag = govPersonDieInnerServiceSMOImpl.saveGovPersonDie(govPersonDiePo);
        if (flag > 0) {

            return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
    }

    private void doGovPersonPo(UserDto user,GovPersonPo govPersonPo,GovOldPersonPo govOldPersonPo) {
        govPersonPo.setGovPersonId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_govGridId));
        Map<String, String> birthdayAgeSex =  getBirthdayAgeSex(govPersonPo.getIdCard());
        govPersonPo.setPersonType("2002");
        govPersonPo.setRamark("手机端死亡登记人员不在人员表生成");
        govPersonPo.setReligiousBelief("无");
        govPersonPo.setNativePlace("中国");
        govPersonPo.setIdType("1");
        govPersonPo.setDatasourceType("999999");
        govPersonPo.setPrePersonName(govPersonPo.getPersonName());
        govPersonPo.setPoliticalOutlook("5012");
        govPersonPo.setPersonSex(birthdayAgeSex.get("sexCode"));
        govPersonPo.setBirthday(birthdayAgeSex.get("birthday"));
        GovPersonDto govPersonDto = new GovPersonDto();
        govPersonDto.setPersonName(govPersonPo.getPersonName());
        govPersonDto.setCaId(govPersonPo.getCaId());
        List<GovPersonDto> govPersonDtos = govPersonInnerServiceSMOImpl.queryGovPersons(govPersonDto);
        if (govPersonDtos == null || govPersonDtos.size() < 1) {
            int flag = govPersonInnerServiceSMOImpl.saveGovPerson(govPersonPo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存固定人口失败");
            }
        } else {
            govPersonPo.setGovPersonId(govPersonDtos.get(0).getGovPersonId());
            int flag = govPersonInnerServiceSMOImpl.updateGovPerson(govPersonPo);
            if (flag < 1) {
                throw new IllegalArgumentException("修改固定人口失败");
            }
        }
        //老人表
        GovOldPersonDto govOldPersonDto = new GovOldPersonDto();
        govOldPersonDto.setPersonName(govPersonPo.getPersonName());
        govOldPersonDto.setIdCard(govPersonPo.getIdCard());
        int count = govOldPersonInnerServiceSMOImpl.queryGovOldPersonsCount(govOldPersonDto);
        if (count < 1) {
            govOldPersonPo.setGovPersonId(govPersonPo.getGovPersonId());
            govOldPersonPo.setOldId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_oldId));
            govOldPersonPo.setContactTel(user.getTel());
            govOldPersonPo.setContactPerson(user.getUserName());
            govOldPersonPo.setTypeId("-1");
            govOldPersonPo.setPersonName(govPersonPo.getPersonName());
            govOldPersonPo.setPersonTel(govPersonPo.getPersonTel());
            govOldPersonPo.setServPerson(user.getUserName());
            govOldPersonPo.setServTel(user.getTel());
            govOldPersonPo.setPersonAge(birthdayAgeSex.get("age"));
            govOldPersonPo.setDatasourceType("999999");
            int flag = govOldPersonInnerServiceSMOImpl.saveGovOldPerson(govOldPersonPo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存失败");
            }
        }
    }


    /**
     * 通过身份证号码获取出生日期(birthday)、年龄(age)、性别(sex)
     * @param idCardNo 身份证号码
     * @return 返回的出生日期格式：1993-05-07   性别格式：1:男，0:女
     */
    public static Map<String, String> getBirthdayAgeSex(String idCardNo) {
        String birthday = "";
        String age = "";
        String sexCode = "";

        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = idCardNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                if (!flag){
                    return new HashMap<String, String>();
                }
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag){
                    return new HashMap<String, String>();
                }
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && idCardNo.length() == 15) {
            birthday = "19" + idCardNo.substring(6, 8) + "-"
                    + idCardNo.substring(8, 10) + "-"
                    + idCardNo.substring(10, 12);
            sexCode = Integer.parseInt(idCardNo.substring(idCardNo.length() - 3, idCardNo.length())) % 2 == 0 ? "0" : "1";
            age = (year - Integer.parseInt("19" + idCardNo.substring(6, 8))) + "";
        } else if (flag && idCardNo.length() == 18) {
            birthday = idCardNo.substring(6, 10) + "-"
                    + idCardNo.substring(10, 12) + "-"
                    + idCardNo.substring(12, 14);
            sexCode = Integer.parseInt(idCardNo.substring(idCardNo.length() - 4, idCardNo.length() - 1)) % 2 == 0 ? "0" : "1";
            age = (year - Integer.parseInt(idCardNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        map.put("age", age);
        map.put("sex", sexCode);
        return map;
    }



}
